package etnorservice.etnor_service.service;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2024/07/02/13:23
 **/
@Service
public class ApiCheckService {
    public ResponseEntity<String> checkUrlStatus(String url) {
        long startTime = System.currentTimeMillis(); // 记录请求开始时间

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet request = new HttpGet(url);
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                int statusCode = response.getStatusLine().getStatusCode();
                String message = (statusCode >= 200 && statusCode < 300) ? "ok" : "error";

                long endTime = System.currentTimeMillis(); // 记录请求结束时间
                long latency = endTime - startTime; // 计算时延

                return ResponseEntity.ok()
                        .body("{\"code\": " + statusCode + ", \"host\": \"" + new URL(url).getHost() + "\", \"msg\": \"" + message + "\", \"latency\": \"" + latency + "ms\"}");
            }
        } catch (IOException e) {
            long endTime = System.currentTimeMillis();
            long latency = endTime - startTime;
            // 即使是异常情况，也返回200状态码，但消息体中包含错误信息
            return ResponseEntity.ok()
                    .body("{\"code\": " + (e instanceof MalformedURLException ? 400 : 500) + ", \"host\": \"\", \"msg\": \"" + (e.getMessage() != null ? e.getMessage() : "服务器错误") + "\", \"latency\": \"" + latency + "ms\"}");
        }
    }
}
